//
//  LBXImageBrowser.m
//  ImageBrowse
//
//  Created by bike on 17/1/20.
//  Copyright © 2017年 bike. All rights reserved.
//

#import "LBXImageBrowser.h"
#import "LBXImageBrowserView.h"

@interface LBXImageBrowser () <UIScrollViewDelegate>

@property (strong, nonatomic) UIScrollView *scrollView;
@property (assign, nonatomic) NSInteger currentIndex;
@property (strong, nonatomic) NSMutableArray *reusableViewsArray;
@property (strong, nonatomic) NSMutableArray *showingViewsArray;
@property (assign, nonatomic) NSInteger imagesNumber;

@end

@implementation LBXImageBrowser

- (void)showImageAtIndex:(NSInteger)index
{
    _currentIndex = index;
    _reusableViewsArray = [NSMutableArray arrayWithCapacity:0];
    _showingViewsArray = [NSMutableArray arrayWithCapacity:0];
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window endEditing:YES];
    
    _scrollView = [[UIScrollView alloc] initWithFrame:window.bounds];
    _scrollView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    _scrollView.bounces = YES;
    _scrollView.alwaysBounceHorizontal = YES;
    _scrollView.alwaysBounceVertical = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.delegate = self;
    _scrollView.pagingEnabled = YES;
    [window addSubview:_scrollView];
    
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapAction:)];
    doubleTap.numberOfTapsRequired = 2;
    [_scrollView addGestureRecognizer:doubleTap];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideImage:)];
    [tap requireGestureRecognizerToFail:doubleTap];
    [_scrollView addGestureRecognizer:tap];
    
    
    if ([_delegate respondsToSelector:@selector(numberOfImagesForImageBrowser:)]) {
        _imagesNumber = [_delegate numberOfImagesForImageBrowser:self];
        _scrollView.contentSize = CGSizeMake(CGRectGetWidth(_scrollView.bounds) * _imagesNumber, CGRectGetHeight(_scrollView.bounds));
        _scrollView.contentOffset = CGPointMake(index * CGRectGetWidth(_scrollView.bounds), 0);
    }
    
    LBXImageBrowserView *browserView = [self addBrowserViewToScrollViewAtIndex:index];
    if (index != 0) {
        [self addBrowserViewToScrollViewAtIndex:index - 1];
    }
    if (index < _imagesNumber - 1) {
        [self addBrowserViewToScrollViewAtIndex:index + 1];
    }
    
    if ([_delegate respondsToSelector:@selector(imageBrowser:imageViewAtIndex:)]) {
        UIImageView *oldImageView = [_delegate imageBrowser:self imageViewAtIndex:index];
        CGRect oldframe = [oldImageView convertRect:oldImageView.bounds toView:browserView];
        browserView.bgScrollView.frame = oldframe;
        browserView.imageView.frame = browserView.bgScrollView.bounds;
    }
    browserView.bgScrollView.alpha = 0;
    CGRect originImageRec = [self originImageRectAtIndex:index];
    [UIView animateWithDuration:0.3 animations:^{
        browserView.bgScrollView.frame = originImageRec;
        browserView.imageView.frame = browserView.bgScrollView.bounds;
        browserView.bgScrollView.alpha = 1;
    } completion:^(BOOL finished) {
        browserView.bgScrollView.frame = originImageRec;
        browserView.imageView.frame = browserView.bgScrollView.bounds;
    }];
}

- (LBXImageBrowserView *)addBrowserViewToScrollViewAtIndex:(NSInteger)index
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"index == %ld", index];
    NSArray *filteredArray = [_showingViewsArray filteredArrayUsingPredicate:predicate];
    if (filteredArray.count) {
        return filteredArray.firstObject;
    }
    else {
        LBXImageBrowserView *browserView;
        if (_reusableViewsArray.count) {
            browserView = (LBXImageBrowserView *)_reusableViewsArray.lastObject;
            [_reusableViewsArray removeObject:browserView];
        }
        else {
            browserView = [LBXImageBrowserView createImageBrowserViewWithFrame:CGRectMake(index * CGRectGetWidth(_scrollView.bounds), 0, CGRectGetWidth(_scrollView.bounds), CGRectGetHeight(_scrollView.bounds))];
        }

        browserView.index = index;
        browserView.backgroundColor = [UIColor clearColor];
        [_scrollView addSubview:browserView];
        [_showingViewsArray addObject:browserView];
        
        if ([_delegate respondsToSelector:@selector(imageBrowser:imageAtIndex:)]) {
            browserView.imageView.image = [_delegate imageBrowser:self imageAtIndex:index];
        }
        
        browserView.bgScrollView.frame = [self originImageRectAtIndex:index];
        browserView.imageView.frame = browserView.bgScrollView.bounds;
        
        
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"index < %ld OR index > %ld", _currentIndex - 1, _currentIndex + 1];
        NSArray *filteredArray = [_showingViewsArray filteredArrayUsingPredicate:predicate];
        
        for (LBXImageBrowserView *filteredBrowserView in filteredArray) {
            [filteredBrowserView removeFromSuperview];
        }
        [_showingViewsArray removeObjectsInArray:filteredArray];
        [_reusableViewsArray addObjectsFromArray:filteredArray];
        
        return browserView;
    }
}

- (CGRect)originImageRectAtIndex:(NSInteger)index
{
    //刚显示出来的时候图片的fram
    CGRect originImageRec;
    
    CGFloat imageHeight;
    CGFloat imageWidth;
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    if ([_delegate respondsToSelector:@selector(imageBrowser:imageAtIndex:)]) {
        UIImage *image = [_delegate imageBrowser:self imageAtIndex:index];
        if (((image.size.height * 1.0) / image.size.width) > ((screenHeight - 200) / screenWidth)) {
            imageHeight = screenHeight - 200;
            imageWidth = imageHeight * image.size.width / image.size.height;
        }
        else {
            imageWidth = screenWidth;
            imageHeight = imageWidth * image.size.height / image.size.width;
        }
        
        originImageRec = CGRectMake((screenWidth - imageWidth) / 2.0, (screenHeight - imageHeight) / 2.0, imageWidth, imageHeight);
    }
    else {
        originImageRec = CGRectZero;
    }
    return originImageRec;
}

//- (void)refreshScrollViewMaximunZoomScale
//{
//    //设置图片最大最小缩放倍数
//    CGFloat originImageViewHeight = _originImageRect.size.height;
//    CGFloat imageHeight = _photoImageView.image.size.height;
//    CGFloat scale = imageHeight / originImageViewHeight * 1.5;
//    _bgScrollView.maximumZoomScale = scale > 2.0 ? scale : 2.0;
//}

#pragma Action

- (void)doubleTapAction:(UITapGestureRecognizer *)tap
{
    //双击放大或者缩小
    UIScrollView *scrollView = (UIScrollView *)tap.view;
    if (scrollView.zoomScale > 1) {
        [scrollView setZoomScale:1.0 animated:YES];
    }
    else {
        [scrollView setZoomScale:2.0 animated:YES];
    }
}

- (void)hideImage:(UITapGestureRecognizer*)tap
{
    UIScrollView *scrollView = (UIScrollView *)tap.view;
    if (_showingViewsArray.count > 0) {
        LBXImageBrowserView *browserView;
        LBXImageBrowserView *tempBrowserView = _showingViewsArray.firstObject;
        if (_currentIndex >= tempBrowserView.index) {
            browserView = _showingViewsArray[_currentIndex - tempBrowserView.index];
            if (browserView.bgScrollView.zoomScale > 1.0) {
                [browserView.bgScrollView setZoomScale:1.0];
            }
            CGRect imageRect = [browserView.imageView convertRect:browserView.imageView.bounds toView:browserView];
            browserView.bgScrollView.frame = browserView.bounds;
            browserView.imageView.frame = imageRect;
            
            CGRect oldframe;
            if ([_delegate respondsToSelector:@selector(imageBrowser:imageViewAtIndex:)]) {
                UIImageView *oldImageView = [_delegate imageBrowser:self imageViewAtIndex:_currentIndex];
                oldframe = [oldImageView convertRect:oldImageView.bounds toView:browserView];
            }
            
            [UIView animateWithDuration:0.3 animations:^{
                browserView.imageView.frame = oldframe;
                browserView.alpha = 0;
            } completion:^(BOOL finished) {
                [scrollView removeFromSuperview];
            }];
        }
        else {
            [scrollView removeFromSuperview];
        }
    }
    else {
        [scrollView removeFromSuperview];
    }
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat contentOffsetX = scrollView.contentOffset.x;
    NSInteger oldIndex = _currentIndex;
    _currentIndex = floorf((contentOffsetX + CGRectGetWidth(scrollView.bounds) / 2) / CGRectGetWidth(scrollView.bounds));
    if (_currentIndex > oldIndex && _currentIndex < _imagesNumber - 1) {
        [self addBrowserViewToScrollViewAtIndex:_currentIndex + 1];
    }
    else if (_currentIndex < oldIndex && _currentIndex > 0) {
        [self addBrowserViewToScrollViewAtIndex:_currentIndex - 1];
    }
}

@end
